package v2

import "errors"

// OrderState 模仿kafka的状态机实现
// kafka.controller.ReplicaStateMachine
// 状态机定义基本状态, 状态机的初始化以及状态转移的监听器
type OrderState interface {
	state() byte
	validPreviousStates() []OrderState
}

type OrderStateMachine struct {
}

type OrderStateContext struct {
	state OrderState
}

func (osm *OrderStateMachine) startup() {
	osm.initializeReplicaState()
	_ = osm.handleStateChanges(OrderStateContext{state: &NewOrder{}}, &NewOrder{})
}

func (osm *OrderStateMachine) initializeReplicaState() {

}

func (osm *OrderStateMachine) handleStateChanges(context OrderStateContext, targetState OrderState) error {
	states := context.state.validPreviousStates()
	if isValidOrderStateTransition(states, targetState) {
		publishEvent(context.state, targetState)
		context.state = targetState
		return nil
	}
	return errors.New("not support err type")
}

func publishEvent(oldState OrderState, newState OrderState) {
	// 监听器
}

func isValidOrderStateTransition(orderStates []OrderState, targetState OrderState) bool {
	for _, state := range orderStates {
		if state.state() == targetState.state() {
			return true
		}
	}
	return false
}

type NewOrder struct {
}

func (n *NewOrder) state() byte {
	return 0x01
}

func (n *NewOrder) validPreviousStates() []OrderState {
	return nil
}

type PayedOrder struct {
}

func (p *PayedOrder) state() byte {
	return 0x03
}

func (p *PayedOrder) validPreviousStates() []OrderState {
	return []OrderState{&PayedOrder{}}
}

type CancelOrder struct {
}

func (c *CancelOrder) state() byte {
	return 0x02
}

func (c *CancelOrder) validPreviousStates() []OrderState {
	return []OrderState{&NewOrder{}, &PayedOrder{}}
}

type DeliveryOrder struct {
}

type ReceivedOrder struct {
}
